package cn.zly.spring.beans.factory.support;

import cn.zly.spring.beans.factory.BeansException;
import cn.zly.spring.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * JDK 实例化策略
 * @author zhanglianyong
 * @date 2024/12/30
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

	@Override
	public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) {
		Class beanClass = beanDefinition.getBeanClass();
		try {
			if (null != constructor) {
				return beanClass.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
			} else {
				return beanClass.getDeclaredConstructor().newInstance();
			}
		} catch (InstantiationException | IllegalAccessException | InvocationTargetException |
		         NoSuchMethodException e) {
			throw new BeansException("实例化Bean [ " + beanClass.getName() + "]", e);
		}
	}
}
